package co.yixiang.yshop.module.crm.service.crmworkwxuser;

import co.yixiang.yshop.framework.common.exception.ErrorCode;
import co.yixiang.yshop.module.crm.dal.dataobject.crmworkwxconfig.CrmWorkWxConfigDO;
import co.yixiang.yshop.module.crm.service.crmworkwxconfig.CrmWorkWxConfigService;
import co.yixiang.yshop.module.system.api.user.AdminUserApi;
import co.yixiang.yshop.module.system.api.user.dto.AdminUserRespDTO;
import co.yixiang.yshop.module.system.api.user.dto.UserSaveDTO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;
import me.chanjar.weixin.cp.bean.Gender;
import me.chanjar.weixin.cp.bean.WxCpUser;
import me.chanjar.weixin.cp.bean.user.WxCpDeptUserResult;
import me.chanjar.weixin.cp.config.impl.WxCpDefaultConfigImpl;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import co.yixiang.yshop.module.crm.controller.admin.crmworkwxuser.vo.*;
import co.yixiang.yshop.module.crm.dal.dataobject.crmworkwxuser.CrmWorkWxUserDO;
import co.yixiang.yshop.framework.common.pojo.PageResult;
import co.yixiang.yshop.framework.common.pojo.PageParam;
import co.yixiang.yshop.framework.common.util.object.BeanUtils;

import co.yixiang.yshop.module.crm.dal.mysql.crmworkwxuser.CrmWorkWxUserMapper;

import static co.yixiang.yshop.framework.common.exception.util.ServiceExceptionUtil.exception;
import static co.yixiang.yshop.module.crm.enums.ErrorCodeConstants.*;

/**
 * 企业微信员工 Service 实现类
 *
 * @author yshop
 */
@Service
@Validated
@Slf4j
public class CrmWorkWxUserServiceImpl implements CrmWorkWxUserService {

    @Resource
    private CrmWorkWxUserMapper workWxUserMapper;
    @Resource
    private CrmWorkWxConfigService workWxConfigService;
    @Resource
    private AdminUserApi adminUserApi;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createWorkWxUser() {
        WxCpDefaultConfigImpl configStorage = new WxCpDefaultConfigImpl();

        CrmWorkWxConfigDO workWxConfig = workWxConfigService.getWorkWxConfig(0);

        configStorage.setCorpId(workWxConfig.getCorpId());
        configStorage.setAgentId(Integer.valueOf(workWxConfig.getAgentId()));
        configStorage.setCorpSecret(workWxConfig.getContactsSecret());

        WxCpServiceImpl service = new WxCpServiceImpl();
        service.setWxCpConfigStorage(configStorage);
        try{
            WxCpDeptUserResult wxCpDeptUserResult = service.getUserService().getUserListId("",100);
            //获取员工ID列表
            List<WxCpDeptUserResult.DeptUserList> deptUser = wxCpDeptUserResult.getDeptUser();
            //获取员工详情,这里的需要重新配置下不然会提示ip不允许
            WxCpDefaultConfigImpl configStorage2 = new WxCpDefaultConfigImpl();
            configStorage2.setCorpSecret(workWxConfig.getSecret());
            configStorage2.setCorpId(workWxConfig.getCorpId());
            configStorage2.setAgentId(Integer.valueOf(workWxConfig.getAgentId()));
            WxCpServiceImpl service2 = new WxCpServiceImpl();
            service2.setWxCpConfigStorage(configStorage2);
            deptUser.forEach(u -> {
                CrmWorkWxUserDO workWxUserDO = workWxUserMapper.selectOne(new LambdaQueryWrapper<CrmWorkWxUserDO>()
                        .eq(CrmWorkWxUserDO::getUserid,u.getUserId()));
                if(workWxUserDO == null){
                    try {
                        WxCpUser wxCpUser = service2.getUserService().getById(u.getUserId());
                        CrmWorkWxUserDO workWxUserDO2 = CrmWorkWxUserDO.builder()
                                .corpId(workWxConfig.getSecret())
                                .userid(u.getUserId())
                                .name(wxCpUser.getName())
                                .mobile(wxCpUser.getMobile())
                                .email(wxCpUser.getEmail())
                                .avatar(wxCpUser.getAvatar())
                                .gender(Integer.valueOf(Gender.UNDEFINED.getCode()))
                                .position(wxCpUser.getPosition())
                                .qrCode(wxCpUser.getQrCode())
                                .build();
                        //添加到后台用户表
                        UserSaveDTO userSaveDTO = new UserSaveDTO();
                        userSaveDTO.setUsername(u.getUserId());
                        userSaveDTO.setNickname(wxCpUser.getName());
                        userSaveDTO.setMobile(wxCpUser.getMobile());
                        userSaveDTO.setEmail(wxCpUser.getAvatar());
                        userSaveDTO.setEmail(wxCpUser.getEmail());
                        userSaveDTO.setPassword("123456789");
                        userSaveDTO.setDeptId(workWxConfig.getDeptId());
                        Long id = adminUserApi.createNewUser(userSaveDTO);
                        workWxUserDO2.setAdminId(id);
                        workWxUserMapper.insert(workWxUserDO2);
                    }catch (WxErrorException e){
                        log.error("获取员工详情失败:{}", e.getMessage());
                        throw exception(new ErrorCode(202502101,"获取员工详情失败"));
                    }


                }


            });
        }catch (Exception e){
            log.error("同步员工失败:{}", e.getMessage());
            throw exception(new ErrorCode(202502100,"同步员工失败"));
        }


    }

    @Override
    public void updateWorkWxUser(CrmWorkWxUserSaveReqVO updateReqVO) {
        // 校验存在
        validateWorkWxUserExists(updateReqVO.getId());
        // 更新
        CrmWorkWxUserDO updateObj = BeanUtils.toBean(updateReqVO, CrmWorkWxUserDO.class);
        workWxUserMapper.updateById(updateObj);
    }

    @Override
    public void deleteWorkWxUser(Long id) {
        // 校验存在
        validateWorkWxUserExists(id);
        // 删除
        workWxUserMapper.deleteById(id);
    }

    private void validateWorkWxUserExists(Long id) {
        if (workWxUserMapper.selectById(id) == null) {
            throw exception(WORK_WX_USER_NOT_EXISTS);
        }
    }

    @Override
    public CrmWorkWxUserDO getWorkWxUser(Long id) {
        return workWxUserMapper.selectById(id);
    }

    @Override
    public PageResult<CrmWorkWxUserRespVO> getWorkWxUserPage(CrmWorkWxUserPageReqVO pageReqVO) {
        PageResult<CrmWorkWxUserDO> pageResult = workWxUserMapper.selectPage(pageReqVO);
        PageResult<CrmWorkWxUserRespVO> pageResult1 = BeanUtils.toBean(pageResult, CrmWorkWxUserRespVO.class);
        pageResult1.getList().forEach(u -> {
            AdminUserRespDTO adminUserRespDTO = adminUserApi.getUser(u.getAdminId());
            u.setAdminName(adminUserRespDTO.getNickname());
        });
        return pageResult1;
    }

}